/*
 * Copyright 1999-2018 Alibaba Group Holding Ltd.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.alibaba.nacos.console.security.nacos;

import com.alibaba.nacos.api.common.Constants;
import com.alibaba.nacos.common.utils.Objects;
import com.alibaba.nacos.config.server.auth.RoleInfo;
import com.alibaba.nacos.console.security.AuthenticationStatus;
import com.alibaba.nacos.console.security.nacos.roles.NacosRoleServiceImpl;
import com.alibaba.nacos.console.security.nacos.users.NacosUser;
import com.alibaba.nacos.console.utils.RsaUtil;
import com.alibaba.nacos.core.auth.AccessException;
import com.alibaba.nacos.core.auth.AuthManager;
import com.alibaba.nacos.core.auth.Permission;
import com.alibaba.nacos.core.auth.User;
import com.alibaba.nacos.core.utils.Loggers;
import io.jsonwebtoken.ExpiredJwtException;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.security.GeneralSecurityException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import static com.alibaba.nacos.console.security.AuthenticationStatus.LOGIN_FAIL_WAIT_MINUTE;
import static com.alibaba.nacos.console.security.AuthenticationStatus.MAX_LOGIN_COUNT;

/**
 * Builtin access control entry of Nacos.
 *
 * @author nkorange
 * @since 1.2.0
 */
@Component
public class NacosAuthManager implements AuthManager {

    private static final String TOKEN_PREFIX = "Bearer ";

    /**
     * 登陆失败统计变量
     */
    private static final Map<String, AuthenticationStatus> STATUS_MAP = new HashMap<>();

    @Autowired
    private JwtTokenManager tokenManager;

    @Autowired
    private AuthenticationManager authenticationManager;

    @Autowired
    private NacosRoleServiceImpl roleService;

    @Autowired
    Environment environment;

    @Override
    public User login(Object request) throws AccessException {
        HttpServletRequest req = (HttpServletRequest) request;
        String token = resolveToken(req);
        if (StringUtils.isBlank(token)) {
            throw new AccessException("user not found!");
        }

        try {
            tokenManager.validateToken(token);
        } catch (ExpiredJwtException e) {
            throw new AccessException("token expired!");
        } catch (Exception e) {
            throw new AccessException("token invalid!");
        }

        Authentication authentication = tokenManager.getAuthentication(token);
        SecurityContextHolder.getContext().setAuthentication(authentication);

        String username = authentication.getName();
        NacosUser user = new NacosUser();
        user.setUserName(username);
        user.setToken(token);
        List<RoleInfo> roleInfoList = roleService.getRoles(username);
        if (roleInfoList != null) {
            for (RoleInfo roleInfo : roleInfoList) {
                if (roleInfo.getRole().equals(NacosRoleServiceImpl.GLOBAL_ADMIN_ROLE)) {
                    user.setGlobalAdmin(true);
                    break;
                }
            }
        }

        return user;
    }

    @Override
    public void auth(Permission permission, User user) throws AccessException {
        if (Loggers.AUTH.isDebugEnabled()) {
            Loggers.AUTH.debug("auth permission: {}, user: {}", permission, user);
        }

        if (!roleService.hasPermission(user.getUserName(), permission)) {
            throw new AccessException("authorization failed!");
        }
    }

    /**
     * Get token from header.
     */
    private String resolveToken(HttpServletRequest request) throws AccessException {
        String bearerToken = request.getHeader(NacosAuthConfig.AUTHORIZATION_HEADER);
        if (StringUtils.isNotBlank(bearerToken) && bearerToken.startsWith(TOKEN_PREFIX)) {
            return bearerToken.substring(7);
        }
        bearerToken = request.getParameter(Constants.ACCESS_TOKEN);
        if (StringUtils.isBlank(bearerToken)) {
            String userName = request.getParameter("username");
            String password = request.getParameter("password");
            byte[] bytes = new byte[0];
            try {
                bytes = RsaUtil.decryptByPrivateKey(password, getRsaPrivateKey());
            } catch (GeneralSecurityException e) {
                throw new AccessException("密钥解密失败。");
            }
            String plainText = new String(bytes);
            bearerToken = resolveTokenFromUser(userName, plainText);
        }

        return bearerToken;
    }

    private String getRsaPrivateKey() {
        return environment.getProperty(RSA_PRIVATE_KEY);
    }

    private String resolveTokenFromUser(String userName, String rawPassword) throws AccessException {

        try {
            if (!isLoginPermited(userName)) {
                throw new AccessException("登陆失败次数过多，拒绝访问！");
            }
            UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(userName,
                rawPassword);
            authenticationManager.authenticate(authenticationToken);
        } catch (AuthenticationException e) {
            loginFail(userName);
            throw new AccessException("unknown user!");
        }
        loginSucceedOrTimePermited(userName);
        return tokenManager.createToken(userName);
    }

    boolean isLoginPermited(String loginName) {
        boolean permited = true;
        AuthenticationStatus authenticationStatus = STATUS_MAP.get(loginName);
        // 检查是否有登陆失效
        if (Objects.nonNull(authenticationStatus)) {
            long firstLoginFailTime = authenticationStatus.getFirstFailTime();
            long now = System.currentTimeMillis();
            if (now - firstLoginFailTime > TimeUnit.MINUTES.toMillis(LOGIN_FAIL_WAIT_MINUTE)) {
                loginSucceedOrTimePermited(loginName);
            } else {
                permited = authenticationStatus.getFailCount() <= MAX_LOGIN_COUNT;
            }
        }
        return permited;
    }

    void loginFail(String loginName) {
        AuthenticationStatus authnStatus = getAuthnStatus(loginName);
        authnStatus.setLastFailTime(System.currentTimeMillis());
        authnStatus.loginFail();
    }

    void loginSucceedOrTimePermited(String loginName) {
        AuthenticationStatus authenticationStatus = STATUS_MAP.get(loginName);
        if (Objects.nonNull(authenticationStatus)) {
            authenticationStatus.resetLogFail();
            authenticationStatus.setLastFailTime(null);
            authenticationStatus.setFirstFailTime(null);
        }
    }

    AuthenticationStatus getAuthnStatus(String loginName) {
        AuthenticationStatus authenticationStatus = STATUS_MAP.get(loginName);
        if (java.util.Objects.isNull(authenticationStatus)) {
            authenticationStatus = new AuthenticationStatus();
            authenticationStatus.setLoingName(loginName);
            authenticationStatus.setFirstFailTime(System.currentTimeMillis());
            synchronized (STATUS_MAP) {
                STATUS_MAP.put(loginName, authenticationStatus);
            }
        }
        // 如果首次登陆失败时间为空，则代表了登陆是
        if (Objects.isNull(authenticationStatus.getFirstFailTime())) {
            authenticationStatus.setFirstFailTime(System.currentTimeMillis());
        }
        return authenticationStatus;
    }
}
